<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-card">
        <div class="register-header">
          <h2>用户注册</h2>
          <p>加入 LetHear 大家庭</p>
        </div>

        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="register-form"
          size="large"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              prefix-icon="Message"
              clearable
            />
          </el-form-item>

          <el-form-item prop="nickname">
            <el-input
              v-model="registerForm.nickname"
              placeholder="昵称（可选）"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item>
            <div class="form-options">
              <el-checkbox v-model="agreeTerms">
                我已阅读并同意
                <el-link type="primary" @click="showUserAgreement">《用户协议》</el-link>
              </el-checkbox>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              :disabled="!agreeTerms"
              @click="handleRegister"
              class="register-button"
            >
              {{ loading ? "注册中..." : "注册" }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="register-footer">
          <span>已有账号？</span>
          <el-link type="primary" @click="$router.push('/login')">立即登录</el-link>
        </div>
      </div>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog
      v-model="agreementVisible"
      title="用户服务协议"
      width="90%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="agreement-dialog"
    >
      <div class="agreement-container">
        <UserAgreement class="in-dialog" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="agreementVisible = false">关闭</el-button>
          <el-button type="primary" @click="agreeAndClose"> 我已阅读并同意该协议 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import { register } from "@/api/auth";
import type { RegisterRequest } from "@/types";
import UserAgreement from "@/components/UserAgreement.vue";

const router = useRouter();
const registerFormRef = ref<FormInstance>();
const loading = ref(false);
const agreeTerms = ref(false);
const agreementVisible = ref(false);

// 注册表单
const registerForm = reactive<RegisterRequest>({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  agreeToTerms: false,
});

// 自定义验证器
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "用户名只能包含字母、数字和下划线", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  nickname: [{ max: 50, message: "昵称长度不能超过50个字符", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    // 验证表单
    await registerFormRef.value.validate();

    if (!agreeTerms.value) {
      ElMessage.warning("请同意用户协议");
      return;
    }

    loading.value = true;

    // 设置同意协议状态
    registerForm.agreeToTerms = agreeTerms.value;

    // 执行注册
    await register(registerForm);

    ElMessage.success("注册成功！请登录");
    router.push("/login");
  } catch (error: any) {
    console.error("Register error:", error);
    ElMessage.error(error.response?.data?.message || error.message || "注册失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 显示用户协议
const showUserAgreement = () => {
  agreementVisible.value = true;
};

// 同意协议并关闭对话框
const agreeAndClose = () => {
  agreeTerms.value = true;
  agreementVisible.value = false;
  ElMessage.success("感谢您同意我们的用户协议");
};
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;

  .register-container {
    width: 100%;
    max-width: 450px;

    .register-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      padding: 40px;

      .register-header {
        text-align: center;
        margin-bottom: 30px;

        h2 {
          color: #2c3e50;
          font-size: 28px;
          font-weight: 600;
          margin-bottom: 8px;
        }

        p {
          color: #606266;
          font-size: 14px;
        }
      }

      .register-form {
        .el-form-item {
          margin-bottom: 20px;
        }

        .form-options {
          width: 100%;

          .el-checkbox {
            color: #606266;
            font-size: 14px;
          }
        }

        .register-button {
          width: 100%;
          height: 44px;
          font-size: 16px;
          margin-top: 10px;
        }
      }

      .register-footer {
        text-align: center;
        margin-top: 30px;
        color: #606266;
        font-size: 14px;

        .el-link {
          margin-left: 5px;
        }
      }
    }
  }
}

// 用户协议对话框样式
:global(.agreement-dialog) {
  .el-dialog__header {
    background: #ffffff;
    border-bottom: 1px solid #e4e7ed;
    padding: 20px 24px;

    .el-dialog__title {
      color: #303133;
      font-size: 18px;
      font-weight: 600;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #909399;
        font-size: 20px;

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  .el-dialog__body {
    padding: 0 !important;
    max-height: 70vh !important;
    overflow-y: auto !important;
    background: #ffffff;

    .agreement-container {
      padding: 0;
      height: 100%;
      overflow-y: auto;
    }
  }

  .el-dialog__footer {
    background: #fafafa;
    border-top: 1px solid #e4e7ed;
    padding: 16px 24px;

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;

      .el-button {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 500;

        &:first-child {
          color: #606266;
          border-color: #dcdfe6;

          &:hover {
            color: #409eff;
            border-color: #c6e2ff;
            background-color: #ecf5ff;
          }
        }

        &:last-child {
          background: #409eff;
          border-color: #409eff;

          &:hover {
            background: #66b1ff;
            border-color: #66b1ff;
          }
        }
      }
    }
  }

  // 对话框整体样式
  .el-dialog {
    border-radius: 12px;
    box-shadow: 0 12px 32px 4px rgba(0, 0, 0, 0.04), 0 8px 20px rgba(0, 0, 0, 0.08);
    overflow: hidden;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .register-page {
    padding: 10px;

    .register-container {
      .register-card {
        padding: 30px 20px;

        .register-header {
          h2 {
            font-size: 24px;
          }
        }
      }
    }
  }

  // 移动端协议对话框样式
  :global(.agreement-dialog) {
    width: 95% !important;
    margin: 5vh auto !important;

    .el-dialog__body {
      max-height: 60vh !important;
      overflow-y: auto !important;

      .agreement-container {
        padding: 0;
        height: 100%;
        overflow-y: auto;
      }
    }

    .el-dialog__footer {
      .dialog-footer {
        flex-direction: column;
        gap: 8px;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
